package org.example.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebServlet("/response/json")
public class ResponseJSON extends HttpServlet {

    private static final ObjectMapper M = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User u1 = new User();
        u1.setUsername("哈哈");
        u1.setPassword("123");
        User u2 = new User();
        u2.setUsername("是看得见");
        u2.setPassword("456");
        Classes c1 = new Classes();
        c1.setId(1);
        c1.setName("中文系1班");
        c1.setStudents(Arrays.asList(u1,u2));
        //返回给前端一个json字符串
        String json = M.writeValueAsString(c1);
        //设置响应正文数据格式
        resp.setContentType("application/json");
        //设置响应正文的编码
        resp.setCharacterEncoding("UTF-8");
        //设置到body中
        resp.getWriter().write(json);
    }
}
